/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.order;

import com.lxk.event.oms.enums.OrderEnums;
import com.lxk.oms.order.domain.bo.OmsOrderBo;
import com.lxk.oms.order.domain.bo.OmsOrderItemBo;
import com.lxk.oms.order.domain.vo.OmsOrderItemVo;
import com.lxk.oms.order.domain.vo.OmsOrderVo;
import com.lxk.oms.order.service.IOmsOrderItemService;
import com.lxk.oms.order.service.IOmsOrderService;
import com.lxk.service.idgenerator.GeneratorType;
import com.lxk.service.idgenerator.IdGeneratorServiceApi;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.log.LFLog;
import com.yomahub.liteflow.log.LFLoggerManager;
import lombok.AllArgsConstructor;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.ValidationUtils;
import org.dromara.common.core.validate.AddGroup;

import java.math.BigDecimal;
import java.util.List;

/**
 * 普通订单创建
 *
 * @author heyi
 * 2024/8/20
 */

@LiteflowComponent(value = FlowOrderNodeConst.CREATE_ORDER)
@AllArgsConstructor
public class OrderCreateNode extends NodeComponent {
    private final LFLog log = LFLoggerManager.getLogger(FlowExecutor.class);
    private final IOmsOrderService omsOrderService;
    private final IdGeneratorServiceApi idGeneratorServiceApi;
    private final IOmsOrderItemService orderItemService;

    @Override
    public void process() throws Exception {

        OrderContext contextBean = getContextBean(OrderContext.class);
        OmsOrderBo add = MapstructUtils.convert(contextBean, OmsOrderBo.class);
        add.setOrderNo(idGeneratorServiceApi.generatorSn(GeneratorType.ORDER_T));
        add.setOrderType(contextBean.getOrderType().getCode());
        add.setStatus(OrderEnums.OrderStatus.CREATE_0.getCode());
        add.setUserDelFlag(UserConstants.DEL_FLAG_NORMAL);
        add.setMerDelFlag(UserConstants.DEL_FLAG_NORMAL);
        add.setDivideStatus(OrderEnums.DivideStatus.NOT.getCode());
        add.setRefundAmount(BigDecimal.ZERO);
        add.setRefundStatus(OrderEnums.RefundStatus.NOT.getCode());
        add.setPostStatus(OrderEnums.PostStatus.INIT_0.getCode());
        add.setDeliveryType(contextBean.getDeliveryType().getCode());
        add.setPayStatus(OrderEnums.PayStatus.NOT.getCode());
        add.setNeedStock(contextBean.getNeedStockCode());
        ValidationUtils.validate(add, AddGroup.class);
        List<OmsOrderItemBo> orderItemBoList = contextBean.getOrderItemBoList();
        if (contextBean.getSaveDb()) {
            Boolean success = omsOrderService.insertByBo(add);
            if (success) {
                Long orderId = add.getId();
                orderItemBoList.forEach(addItem -> {
                    addItem.setOrderId(orderId);
                    addItem.setOrderItemSn(idGeneratorServiceApi.generatorSn(GeneratorType.ORDER_ITEM));
                    ValidationUtils.validate(addItem, AddGroup.class);
                    orderItemService.insertByBo(addItem);
                });
            } else {
                log.error("生成订单失败，请联管理员,{}", add);
                throw new ServiceException("生成订单失败，请联管理员");
            }
        }
        OrderContext.OrderResult result = new OrderContext.OrderResult();
        result.setOrder(MapstructUtils.convert(add, OmsOrderVo.class));
        result.setOrderItemVoList(MapstructUtils.convert(orderItemBoList, OmsOrderItemVo.class));
        contextBean.setOrderResult(result);
    }

    @Override
    public boolean isAccess() {
//        OrderContext contextBean = getContextBean(OrderContext.class);
//        OrderEnums.OrderType orderType = contextBean.getOrderType();
//        return orderType == OrderEnums.OrderType.ORDER_NORMAL;
        return true;
    }

    @Override
    public void onSuccess() {

    }
}
